<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <text class="title">订单管理</text>
    </view>

    <!-- 订单状态Tab -->
    <view class="order-tabs">
      <view class="tab-item" :class="{ active: currentTab === 2 }" @click="switchTab(2)">
        <text>待处理</text>
        <text class="badge" v-if="pendingCount > 0">{{ pendingCount }}</text>
      </view>
      <view class="tab-item" :class="{ active: currentTab === 3 }" @click="switchTab(3)">
        <text>进行中</text>
      </view>
      <view class="tab-item" :class="{ active: currentTab === 4 }" @click="switchTab(4)">
        <text>已完成</text>
      </view>
    </view>

    <!-- 订单列表 -->
    <scroll-view scroll-y class="order-list" @scrolltolower="loadMore" :scroll-top="scrollTop" :style="{ height: 'calc(100vh - 200rpx)' }">
      <view class="order-item" v-for="(item, index) in filteredOrders" :key="index">
        <view class="order-header">
          <text class="order-no">订单编号: {{ item.id }}</text>
          <text class="order-status" :class="getStatusClass(item.status)">{{ getStatusText(item.status) }}</text>
        </view>
        
        <view class="goods-info" v-for="(g, gIndex) in item.goods" :key="gIndex">
          <image class="goods-image" :src="g.image" mode="aspectFill"></image>
          <view class="goods-detail">
            <view class="goods-name-info">
              <text class="goods-name">{{ g.name }}</text>
              <text class="goods-spec" v-if="g.specifications">{{ formatSpecifications(g.specifications) }}</text>
            </view>
            <view class="goods-price-info">
              <text class="goods-quantity">x{{ g.quantity }}</text>
              <text class="goods-price">¥{{ g.price }}</text>
            </view>
          </view>
        </view>
        
        <view class="order-footer">
          <text class="order-time">{{ item.createTime }}</text>
          <text class="order-total">实付金额: ¥{{ item.actualPay }}</text>
        </view>

        <view class="order-delivery-time" v-if="item.deliveryType === 1">
          <text class="delivery-time-label">预约送达时间: </text>
          <text class="delivery-time-value">{{ item.deliveryTimeType === 1 ? '尽快送达' : item.scheduleTime }}</text>
        </view>
        
        <view class="order-actions" v-if="item.status === 2">
          <button class="reject-btn" @click="handleReject(item.id)">拒单</button>
          <button class="accept-btn" @click="handleAccept(item.id)">接单</button>
        </view>
        
        <view class="order-actions" v-if="item.status === 3 && item.merchantProcess === 1">
          <button class="finish-meal-btn" @click="handleFinishMeal(item.id)">出餐</button>
          <button class="detail-btn" @click="navigateToDetail(item)">订单详情</button>
        </view>
        
        <view class="order-actions" v-if="(item.status === 3 && item.merchantProcess !== 1) || item.status === 4">
          <button class="detail-btn" @click="navigateToDetail(item)">订单详情</button>
        </view>
      </view>

    <view class="loading-text" v-if="loading">加载中...</view>
    <view class="no-more" v-if="finished">没有更多了</view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import {getMerchantId} from '@/utils/merchant.js';
import { getMerchantOrderPage, getPendingOrderCount, acceptOrder, rejectOrder, finishMeal } from '@/api/order.js';

const currentTab = ref(2);
const pendingCount = ref(0);
const filteredOrders = ref([]);
const merchantId = ref(null);
const loading = ref(false);
const finished = ref(false);
const pageNo = ref(1);
const pageSize = ref(10);
const scrollTop = ref(0);

const loadMore = () => {
  if (!finished.value && !loading.value) {
    loadOrders();
  }
};

const fetchPendingCount = async () => {
  try {
    const resp = await getPendingOrderCount(merchantId.value);
    pendingCount.value = resp.data;
  } catch (error) {
    console.error('获取待处理订单数量失败:', error);
  }
};

const formatSpecifications = (specsStr) => {
  try {
    const specs = JSON.parse(specsStr);
    if (!Array.isArray(specs)) return specsStr;
    return specs.map(spec => spec.value).join(',');
  } catch (e) {
    return specsStr;
  }
};

const loadOrders = async (reset = false) => {
  console.log('[loadOrders] start, reset:', reset, 'currentTab:', currentTab.value, 'pageNo:', pageNo.value, 'finished:', finished.value, 'loading:', loading.value);
  if (reset) {
    pageNo.value = 1;
    finished.value = false;
    filteredOrders.value = [];
  }
  if (loading.value || finished.value) {
    console.log('[loadOrders] blocked, loading or finished');
    return;
  }
  loading.value = true;
  const params = { 
    merchantId: merchantId.value, 
    status: currentTab.value,
    pageNo: pageNo.value,
    pageSize: pageSize.value
  };
  try {
    const resp = await getMerchantOrderPage(params);
    if (resp && resp.data) {
      const newList = resp.data.list;
      if (reset) {
        filteredOrders.value = newList;
      } else {
        filteredOrders.value = [...filteredOrders.value, ...newList];
      }
      if (filteredOrders.value.length >= resp.data.total) {
        finished.value = true;
      } else {
        pageNo.value++;
      }
    } else {
      filteredOrders.value = reset ? [] : filteredOrders.value;
    }
  } catch (e) {
    filteredOrders.value = reset ? [] : filteredOrders.value;
    pendingCount.value = 0;
    finished.value = true;
    uni.showToast({ title: '订单获取失败', icon: 'none' });
    console.error('[loadOrders] error:', e);
  } finally {
    loading.value = false;
    console.log('[loadOrders] end, finished:', finished.value, 'loading:', loading.value);
  }
  fetchPendingCount();
};

const switchTab = (tab) => {
  if (currentTab.value !== tab) {
    currentTab.value = tab;
    pageNo.value = 1;
    finished.value = false;
    filteredOrders.value = [];
    loadOrders(true);
  }
};

const handleAccept = async (orderId) => {
  uni.showModal({
    title: '确认接单',
    content: '确定要接单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await acceptOrder(orderId);
          uni.showToast({ title: '接单成功', icon: 'success' });
          loadOrders(true);
        } catch (e) {
          console.error('接单失败:', e);
          uni.showToast({ title: e.data?.message || '接单失败', icon: 'none' });
        }
      }
    }
  });
};

const getStatusText = (status) => {
  const statusMap = {
    2: '待处理',
    3: '进行中',
    4: '已完成'
  };
  return statusMap[status] || '未知状态';
};

const getStatusClass = (status) => {
  const statusClassMap = {
    2: 'status-pending',
    3: 'status-processing',
    4: 'status-completed'
  };
  return statusClassMap[status] || '';
};

const handleReject = async (orderId) => {
  uni.showModal({
    title: '拒单原因',
    content: '',
    editable: true,
    placeholderText: '请输入拒单原因',
    success: async (res) => {
      if (res.confirm) {
        const cancelReason = res.content?.trim();
        if (!cancelReason) {
          uni.showToast({ title: '请填写拒单原因', icon: 'none' });
          return;
        }
        try {
          await rejectOrder(orderId, cancelReason);
          uni.showToast({ title: '拒单成功', icon: 'success' });
          loadOrders(true);
        } catch (e) {
          console.error('拒单失败:', e);
          uni.showToast({ title: e.data?.message || '拒单失败', icon: 'none' });
        }
      }
    }
  });
};

const handleFinishMeal = async (orderId) => {
  uni.showModal({
    title: '确认出餐',
    content: '确定要出餐吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await finishMeal(orderId);
          uni.showToast({ title: '出餐成功', icon: 'success' });
          loadOrders(true);
        } catch (e) {
          uni.showToast({ title: '出餐失败', icon: 'none' });
        }
      }
    }
  });
};

const navigateToDetail = (order) => {
  uni.navigateTo({
    url: `/pages/order/detail?id=${order.id}`
  });
};

onShow(() => {
  merchantId.value = getMerchantId();
  loadOrders(true);
});
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #fafafa;
  display: flex;
  flex-direction: column;
}

.header {
  padding: 30rpx 0;
  text-align: center;
  background-color: rgba(255, 255, 255, 0.95);
  position: sticky;
  top: 0;
  z-index: 10;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: $uni-text-color;
}

.order-tabs {
  display: flex;
  justify-content: space-around;
  padding: 24rpx 0;
  background-color: rgba(255, 255, 255, 0.95);
  position: sticky;
  top: 80rpx;
  z-index: 10;
  border-radius: 0 0 24rpx 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.03);

  .tab-item {
    flex: 1;
    text-align: center;
    font-size: 28rpx;
    color: #666;
    position: relative;
    padding-bottom: 12rpx;
    transition: all 0.3s ease;

    &.active {
      color: #ff6b6b;
      font-weight: 600;
      transform: scale(1.05);

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 32rpx;
        height: 4rpx;
        background: linear-gradient(to right, #ff9a9e, #ff6b6b);
        border-radius: 4rpx;
        box-shadow: 0 2rpx 8rpx rgba(255, 107, 107, 0.3);
      }
    }
  }
}

.badge {
  position: absolute;
  top: -10rpx;
  right: -20rpx;
  min-width: 36rpx;
  height: 36rpx;
  padding: 0 8rpx;
  background: linear-gradient(to right, #ff9a9e, #ff6b6b);
  border-radius: 18rpx;
  color: $uni-text-color-inverse;
  font-size: 22rpx;
  text-align: center;
  line-height: 36rpx;
}

.order-list {
  flex: 1;
  padding: 24rpx;
  box-sizing: border-box;
  width: 100%;
}

.order-item {
  background-color: #fff;
  border-radius: 24rpx;
  margin-bottom: 30rpx;
  padding: 36rpx;
  box-shadow: 0 6rpx 24rpx rgba(0, 0, 0, 0.04), 0 2rpx 6rpx rgba(0, 0, 0, 0.02);
  width: 100%;
  box-sizing: border-box;
  transition: transform 0.3s ease, box-shadow 0.3s ease;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.03);
  }
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 24rpx;
  border-bottom: 2rpx solid #f5f5f5;
}

.order-status {
  font-size: 26rpx;
  padding: 6rpx 16rpx;
  border-radius: 24rpx;

  &.status-pending {
    color: #ff8c00;
    background-color: rgba(255, 140, 0, 0.1);
  }

  &.status-processing {
    color: #1989fa;
    background-color: rgba(25, 137, 250, 0.1);
  }

  &.status-completed {
    color: #323233;
    background-color: rgba(50, 50, 51, 0.05);
  }
}

.goods-info {
  display: flex;
  align-items: center;
  margin: 24rpx 0;
}

.goods-image {
  width: 120rpx;
  height: 90rpx;
  border-radius: 16rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
  object-fit: cover;
}

.goods-detail {
  flex: 1;
  overflow: hidden;
  display: flex;
  justify-content: space-between;
}

.goods-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 8rpx;
  font-weight: 500;
}

.goods-spec {
  font-size: 24rpx;
  color: #999;
  background-color: #f9f9f9;
  padding: 4rpx 10rpx;
  border-radius: 8rpx;
  display: inline-block;
}

.goods-price {
  font-size: 28rpx;
  color: #333;
  font-weight: 600;
}

.goods-price-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 24rpx;
  border-top: 2rpx solid #f8f8f8;
}

.order-time {
  font-size: 24rpx;
  color: #999;
}

.order-total {
  font-size: 32rpx;
  color: #ff6b6b;
  font-weight: 600;
}

.order-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 20rpx;

  button {
    flex: 0 0 calc(33.33% - 20rpx);
    margin: 0 10rpx;
    padding: 0 20rpx;
    height: 70rpx;
    line-height: 70rpx;
    border-radius: 35rpx;
    font-size: 28rpx;
    border: 1rpx solid #ddd;
    background-color: #fff;

    &.reject-btn {
      color: #ff6b6b;
      border-color: #ff6b6b;
      
      &:active {
        background-color: rgba(255, 107, 107, 0.1);
      }
    }

    &.accept-btn {
      color: #fff;
      background: linear-gradient(to right, #ff9a9e, #ff6b6b);
      border: none;
      box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.3);
      
      &:active {
        transform: scale(0.95);
      }
    }

    &.finish-meal-btn {
      color: #fff;
      background: linear-gradient(to right, #ff9a9e, #ff6b6b);
      border: none;
      box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.3);
      
      &:active {
        transform: scale(0.95);
      }
    }

    &.detail-btn {
      color: #666;
    }
  }
}
</style>